package com.qyhl.module_home.city.bestone;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.text.SpannableStringBuilder;
import android.text.style.TextAppearanceSpan;
import android.view.View;
import android.widget.TextView;

import com.qyhl.module_home.R;
import com.qyhl.webtv.basiclib.utils.SpanUtils;
import com.qyhl.webtv.commonlib.entity.home.BestoneItemTypeBean;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.List;

public class SearchAdapter extends CommonAdapter<BestoneItemTypeBean> {
    private String inputText;
    private Activity context;

    private View.OnClickListener onClickListener = v -> toCall((String) v.getTag());

    public SearchAdapter(Activity context, List<BestoneItemTypeBean> datas) {
        super(context, R.layout.home_bestone_search, datas);
        this.context = context;
    }

    @Override
    protected void convert(ViewHolder viewHolder, BestoneItemTypeBean bean, int positon) {
        setInput((TextView) viewHolder.getView(R.id.searchTitle), bean.getTitle());
        setInput((TextView) viewHolder.getView(R.id.searchPhone), bean.getPhone());
        viewHolder.getView(R.id.gocall).setTag(bean.getPhone());
        viewHolder.getView(R.id.gocall).setOnClickListener(onClickListener);
    }

    private void setInput(TextView textView, String content) {
        if (content.contains(inputText)) {
            int start = content.indexOf(inputText);
            int end = start + inputText.length();
            String s1 = content.substring(0, start);
            String s2 = content.substring(start, end);
            String s3 = content.substring(end, content.length());
            SpanUtils spanUtils = new SpanUtils(context);
            SpannableStringBuilder spannableStringBuilder = spanUtils.append(s1).append(s2)
                    .setSpans(new TextAppearanceSpan(context, R.style.home_bestone_key)).append(s3).create();
            textView.setText(spannableStringBuilder);
        } else {
            textView.setText(content);
        }
    }

    //手动拨打电话，无需权限
    private void toCall(String phoneNum) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        context.startActivity(intent);
    }


    public void setInputText(String inputText) {
        this.inputText = inputText;
    }
}
